package jmu.edu.yjc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jmu.edu.yjc.Utils.CodeUtil;
import jmu.edu.yjc.Utils.EmailUtil;
import jmu.edu.yjc.Utils.RedisCache;
import jmu.edu.yjc.domain.ResponseResult;
import jmu.edu.yjc.domain.entity.User;
import jmu.edu.yjc.enums.AppHttpCodeEnum;
import jmu.edu.yjc.service.CodeService;
import jmu.edu.yjc.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.swing.text.StringContent;
import javax.validation.constraints.Email;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author yjc
 * @date 2023/4/21 16:09
 */
@Service("codeService")
public class CodeServiceImpl implements CodeService {
    @Resource
    private UserService userService;
    @Autowired
    private EmailUtil emailUtil;
    @Resource
    private RedisCache redisCache;
    @Override
    public ResponseResult getRegisterCode(HttpServletRequest request, String email, String userName) {
        boolean exist = userService.userNameExist(userName);
        if(exist) {
            return ResponseResult.errorResult(AppHttpCodeEnum.USERNAME_EXIST);
        }
        String code = getRandomCode();
        redisCache.setCacheObject("code:" + userName, code,  2, TimeUnit.MINUTES);
        String title = "老年人社区管理与服务平台";
        String content = "尊敬的用户您好您正在注册成为老年人社区管理与服务的平台用户这是您的验证码: "+ code +" 请在120s内完成注册";
        emailUtil.sendMessage(email,title,content);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getForgiveCode(HttpServletRequest request, String email, String userName) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,userName);
        User one = userService.getOne(wrapper);
        if(!one.getEmail().equals(email)) {
            return ResponseResult.errorResult(-1, "所填用户名与邮箱预留邮箱不符");
        }
        String code = getRandomCode();
        redisCache.setCacheObject("code:" + userName, code,  2, TimeUnit.MINUTES);
        String title = "老年人社区管理与服务平台";
        String content = "尊敬的用户您好您正在修改您在老年人社区管理与服务的平台用户的密码这是您的验证码: "+ code +" 请在120s内完成操作";
        emailUtil.sendMessage(email,title,content);
        return ResponseResult.okResult();
    }

    private String getRandomCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int r = random.nextInt(10);
            code.append(String.valueOf(r));
        }
        return code.toString();
    }
}
